<?php
namespace app\app\controller\v1;
use think\Db;
use app\app\util\OnlineUtils;
class ExchangeController extends BaseController{


    /**
     * @return array
     * [用户积分兑换卡]
     */
    public function changeCard()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        $exchange['user_id'] = $user_id;                          //用户id
        $exchange['card_id'] = input('get.card_id');                                   //道具id
        $exchange['created_at'] = time();                                              //兑换时间
        $user_info = Db::name('user')->where('id','eq',$exchange['user_id'] )->find(); //用户信息
        $card_info = Db::name('card')->where('id','eq',$exchange['card_id'] )->find(); //卡片信息
        //如果用户的积分大于卡片所需的积分，才可进行兑换操作
        //兑换卡片，1.添加兑换记录，2.用户积分减少；3.用户的卡片数量加1;卡片的兑换数量加1
        if ( $user_info['integral'] >= $card_info['integral'] ) {
            Db::name('exchange')->insertGetId($exchange);             //添加兑换记录
            //redis添加
            CardUtils::getUserStarCard($user_id,input('card_id'));
            Db::query('update ft_user set integral = integral - '.intval($card_info["integral"]).' where id ='.$exchange['user_id']);  //用户积分减少
            Db::query('update ft_my_card set num = num + 1  where user_id ='.$exchange['user_id'].' and card_id ='.$exchange['card_id']); //卡片的兑换数量加1
            Db::query('update ft_card set exchange = exchange + 1 where id ='.input('card_id')); 
            return ft(200,'兑换成功');
        }else{
            return ft(402,'用户积分不足兑换该卡');
        }


    }

}
